<template>
  <div v-cloak>
    <div class="indexs" ref="container" v-if="status === 200">
      <div
        class="follow acea-row row-between-wrapper"
        v-if="followHid && followUrl && !subscribe"
      >
        <div>点击“立即关注”即可关注公众号</div>
        <div class="acea-row row-middle">
          <div class="bnt" @click="followTap">立即关注</div>
          <span class="iconfont icon-guanbi" @click="closeFollow"></span>
        </div>
      </div>
      <div class="followCode" v-if="followCode">
        <div class="pictrue"><img :src="followUrl" /></div>
        <div class="mask" @click="closeFollowCode"></div>
      </div>
      <div class="header bg-color-main" :class="{fixedHeader: fixedHeader}">
        <div class="acea-row row-between-wrapper">
          <router-link :to="'/search'" class="input acea-row row-middle">
            <span class="iconfont icon-xiazai5"></span>搜索商品
          </router-link>
          <router-link :to="'/customer/list'" class="sign">
            <img :src="require(fixedHeader || categorySelected !== 0 ? '@/assets/images/zhenxing/message-gray.svg' : '@/assets/images/zhenxing/message.svg')" />
            <small :class="[fixedHeader || categorySelected !== 0 ? 'font-color-gray-dk' : 'font-color-white']">消息</small>
          </router-link>
        </div>
        <!-- 可滑动 Tab -->
        <div class="scroll-nav" v-if="categoryList">
          <swiper ref="tabbarSwiper" :options="tabbarSwiperConfig">
              <swiper-slide v-for="(item, index) in categoryList" :key="index" style="width: auto;">
                <span @click="categoryCurrent(index, item.id, item.children)" :class="[categorySelected === index ? 'select' : '']" class="classify">{{ item.cate_name }}</span>
              </swiper-slide>
            </swiper>
        </div>
      </div>

      <!-- 选项卡对应内容 -->
      <div class="slide-page" :class="{down: fixedHeader}">
        <swiper ref="pageSwiper" :options="pageSwiperConfig" @slideChangeTransitionEnd="pageSlide">
          <swiper-slide v-for="(item, index) in categoryList.length" :key="index">
            <div v-if="!categorySelected">
              <!-- 轮播图 -->
              <div class="slider-banner" v-if="banner.length">
                <swiper :options="swiperOption">
                  <swiper-slide v-for="(item, index) in banner" :key="index">
                    <router-link
                      :to="item.wap_url ? item.wap_url : ''"
                      class="search acea-row row-middle"
                    >
                      <img :data-src="item.pic" class="swiper-lazy" />
                      <div class="swiper-lazy-preloader"></div>
                    </router-link>
                  </swiper-slide>
                  <div class="swiper-pagination" slot="pagination"></div>
                </swiper>
              </div>
              <div class="acea-row row-around font-color-main-lt text-center font-xs padding20 quality-serve">
                <span> 大牌品质 </span>
                <span> 工厂价格 </span>
                <span> 分期支付 </span>
                <span> 顺丰包邮 </span>
                <span> 无忧退款</span>
              </div>

              <!-- 图标导航 -->
              <div class="menu acea-row">
                <router-link
                  :to="item.wap_url"
                  class="item"
                  v-for="(item, index) in menuList"
                  :key="index"
                >
                  <div class="pictrue"><img v-lazy="item.pic" alt="img" /></div>
                  <div>{{ item.name }}</div>
                </router-link>
              </div>
              <div class="split-line"></div>
            </div>
            <div v-if="categorySelected">
              <div class="acea-row row-around" style="padding-bottom: .3rem;">
                <div style="width: 25%; margin-top: .3rem;" class="text-center" v-for="(item, index) in categoryItem" :key=index @click="$router.push({ path: `/goodsClassInfo?cid=${categoryId}&sid=${item.id}` })">
                  <img :src="item.pic" alt="icon" style="width: 1rem; overflow: hidden; border-radius: 50%;">
                  <div>{{ item.cate_name }}</div>
                </div>
              </div>
              <div class="split-block"></div>
            </div>
            <!-- 产品列表 -->
            <div class="wrapper">
              <div class="text-center padding20" v-if="!categorySelected">
                <div class="text-underline font-sm">{{ +userInfo.is_new ? '新手特权 仅限首单' : '大牌品质 工厂价格' }}</div>
                <div class="font-color-gold font-xxs">直联大牌制造 每日整点上新</div>
              </div>
              <template>
                <GoodList :isSort="Switch" :categoryId="categoryId" :obj="obj" v-if="categorySelected == index && showList"></GoodList>
              </template>
            </div>
          </swiper-slide>
        </swiper>
        <!-- 底部固定-待拼团订单列表 -->
        <div class="news acea-row row-between-wrapper" v-if="waitCombinationOrderList.length > 0 && showWaitCombinationOrderList && categorySelected === 0">
          <div class="swiper-no-swiping swiperTxt">
            <swiper :options="swiperRoll">
              <swiper-slide
                class="swiper-slide"
                v-for="(item, index) in waitCombinationOrderList"
                :key="index"
              >
                <router-link
                  :to="`/activity/group_detail/${item.id}`"
                  class="acea-row row-between-wrapper"
                  style="flex-wrap: nowrap"
                >
                  <img style="width: 7%; border-radius: 50%;" :src="item.avatar" alt="用户头像">
                  <div class="text line1" style="width: 80%;">{{ item.nickname }} 发起了一起拼</div>
                  <div class="iconfont icon-xiangyou"></div>
                </router-link>
              </swiper-slide>
            </swiper>
          </div>
        </div>
      </div>

      <!-- 优惠券弹窗 -->
      <Coupon-window
        :type="showCouponType"
        :couponList="getCouponList"
        v-if="showCoupon"
        @checked="couponClose"
        @close="couponClose"
      ></Coupon-window>
    </div>
    <loadLogo v-else></loadLogo>
  </div>
</template>
<style scoped>
/deep/ .slide-page .swiper-wrapper {
  height: auto!important;
}

.indexs .follow {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.36);
  height: 0.8rem;
  font-size: 0.28rem;
  color: #fff;
  padding: 0 0.3rem;
}
.indexs .follow .bnt {
  width: 1.6rem;
  height: 0.5rem;
  background-color: #784efa;
  border-radius: 0.25rem;
  font-size: 0.24rem;
  text-align: center;
  line-height: 0.5rem;
}
.indexs .follow .iconfont {
  font-size: 0.3rem;
  margin-left: 0.29rem;
}
.indexs .followCode .pictrue {
  width: 5rem;
  height: 7.2rem;
  border-radius: 12px;
  left: 50%;
  top: 50%;
  margin-left: -2.5rem;
  margin-top: -3.6rem;
  position: fixed;
  z-index: 9;
}
.indexs .followCode .pictrue img {
  width: 100%;
  height: 100%;
}
.indexs .follow {
  z-index: 100000;
}
.indexs .header {
  position: fixed;
  top: 0;
  height: 2rem;
  width: 100%;
  padding: 0.24rem 0.3rem 0 0.3rem;
  z-index: 9;
}
.indexs .header.fixedHeader {
  background-color: #fff!important;
  color: #784efa!important;
  border-bottom: 1px solid #eee;
  z-index: 11;
}
.indexs .header .logo {
  width: 1.27rem;
  height: 0.45rem;
}
.indexs .header .logo img {
  width: 100%;
  height: 100%;
}
.indexs .header .input {
  width: 5.6rem;
  margin-left: 3%;
  /* width: 4.6rem; */
  height: 0.64rem;
  border-radius: 0.32rem;
  background-color: #fff;
  font-size: 0.28rem;
  color: #bbb;
  padding: 0 0.3rem;
}
.indexs .header.fixedHeader .input {
  border: .03rem solid #7f4395;
}
.indexs .header .input .iconfont {
  font-size: 0.33rem;
  margin-right: 0.16rem;
  height: 0.33rem;
}
.indexs .header .sign {
  width: 0.62rem;
  /* height: 0.44rem; */
}
.indexs .header .sign img {
  width: 0.44rem;
  height: 100%;
}
/* 顶部选项卡 */
.scroll-nav { 
  color: #fff; overflow: hidden; margin-top: .1rem; position: relative; z-index: 2;
}
.scroll-nav .classify {
  display: inline-block; padding: .15rem .15rem .1rem; margin-right: .2rem;
}
.scroll-nav .classify.select {
  border-bottom: .03rem solid #fff;
}
.indexs .header.fixedHeader .scroll-nav {
  color: #555;
}
.indexs .header.fixedHeader .scroll-nav .classify.select {
  color: #7f4395;
  border-bottom: .03rem solid #7f4395;
  font-weight: bold;
}

.slide-page {
  margin-top: 2rem;
  padding-bottom: 1rem;
  position: relative;
  z-index: 10;
}
.indexs .slider-page.down {
  z-index: 8;
}

/* 广告图轮播 */
.indexs .slider-banner {
  height: 3.3rem;
  margin: 0 auto;
}

.indexs .slider-banner img {
  width: 100%;
  height: 3.3rem;
}
.indexs .slider-banner .swiper-pagination {
  bottom: 0.15rem;
  text-align: right;
  padding-right: .4rem;
}

/* 商城品质服务 */
.quality-serve span:not(:last-child)::after{
  content: "/";
  color: #ccc;
}

/* 菜单导航 */
.indexs .menu {
  padding-top: 0.38rem;
}
.indexs .menu .item {
  width: 20%;
  text-align: center;
  margin-bottom: 0.35rem;
  color: #555;
  font-size: smaller;
}
.indexs .menu .item .pictrue {
  width: 0.54rem;
  height: 0.54rem;
  margin: 0 auto 0.17rem;
}
.indexs .menu .item .pictrue img {
  width: 100%;
  height: 100%;
}

/* 商品筛选栏 */
.screen-bar {
  height: .9rem;
}
.screen-bar img {
  width: 0.15rem;
  height: 0.19rem;
  margin-left: 0.1rem;
}

/* 商品列表 */
.productList .list{
  padding: 0 0 .7rem;
  margin-top: 0;
}
.productList .list .item {
  border-top: 1px solid #f4f4f4;
  width: 50%;
  margin-top: 0;
}
.productList .list .item:nth-child(odd) {
  border-right: 1px solid #f4f4f4;
}
.productList .list .item.noviceLabel.on::after {
  padding: 0.5% 3%;
  bottom: 20%;
}
.productList .list .item .pictrue {
  height: 3.75rem;
}
.productList .list .item .pictrue img, .productList .list .item .pictrue img.on {
  border-radius: 0;
}

.noCommodity {
  border-top: 3px solid #f5f5f5;
  padding-bottom: 1px;
}

/* 底部待拼团订单列表垂直轮播 */
.indexs .news {
  position: fixed;
  bottom: 8%;
  z-index: 20;
  left: 0;
  right: 0;
  height: 0.6rem;
  width: 6.9rem;
  background-color: rgba(0, 0, 0, .5);
  /* background-image: -moz-linear-gradient(to right, #04d604 0%, #00c17b 100%);
  background-image: -webkit-linear-gradient(to right, #04d604 0%, #00c17b 100%);
  background-image: linear-gradient(to right, #04d604 0%, #00c17b 100%); */
  border-radius: 0.3rem;
  padding: 0 0.28rem;
  margin: 0 auto;
  overflow: hidden;
}
.indexs .news .iconfont {
  font-size: 0.3rem;
  color: #fff;
}
.indexs .news .swiper-slide {
  height: 100%;
}
.indexs .news .swiperTxt {
  /* width: 5.86rem; */
  width: 100%;
  height: 100%;
  line-height: 0.6rem;
  overflow: hidden;
}
.indexs .news .swiperTxt .swiper-container {
  height: 100%;
}
.indexs .news .swiperTxt .text {
  /* width: 5.55rem; */
  color: #fff;
  font-size: 0.26rem;
}
.indexs .news .swiperTxt .iconfont {
  font-size: 0.28rem;
  color: #fff;
}
.indexs .wrapper {
  width: 100%;
  background-color: #fff;
  margin-top: 0.2rem;
}
.indexs .wrapper .title {
  font-size: 0.34rem;
  font-weight: bold;
  color: #282828;
  height: 0.97rem;
}
.indexs .wrapper .title img {
  width: 0.42rem;
  height: 0.26rem;
  display: block;
}
.indexs .wrapper .title .text {
  padding: 0 0.2rem;
}
.indexs .wrapper .title .right {
  transform: rotate(180deg);
  -webkit-transform: rotate(180deg);
  -ms-transform: rotate(180deg);
  -o-transform: rotate(180deg);
  -moz-transform: rotate(180deg);
}

</style>
<script>
import "@assets/css/swiper.min.css";
import { swiper, swiperSlide } from "vue-awesome-swiper";
import { getHomeData, getShare, follow } from "@api/public";
import { getWaitCombinationList } from "@api/activity";
import { getCategory, getProducts } from "@api/store";
import { getCoupon, getCouponReceive, getUserInfo, queryTaskFinished, taskFinish } from "@api/user";
import CouponWindow from "@components/CouponWindow";
import cookie from "@utils/store/cookie";
import { openShareAll } from "@libs/wechat";
import { isWeixin } from "@utils/index";
import GoodList from "@components/GoodListIndex";
import { backTop } from "@utils/common.js";
import { mapGetters } from "vuex";

var vm = null;
const HAS_COUPON_WINDOW = "has_coupon_window";
export default {
  name: "Index",
  components: {
    swiper,
    swiperSlide,
    GoodList,
    CouponWindow
  },
  props: {},
  data: function() {
    return {
      fixedHeader: false,
      status: 0,
      followUrl: "",
      followHid: true,
      subscribe: false,
      followCode: false,
      logoUrl: "",
      banner: [],
      waitCombinationOrderList: [], //待拼团订单列表
      showWaitCombinationOrderList: true,
      categoryList: [], 
      categorySelected: 0,
      categoryItem: [],
      categoryId: 0,
      menuList: [{
          name: '服饰鞋包',
          pic: require('@/assets/images/zhenxing/index-menu-icon/clothes.png'),
          url: '/pages/user_sgin/index',
          show: '2',
          wap_url: '/goodsClassInfo?cid=14&sid=15'
        }, {
          name: '定制咖啡',
          pic: require('@/assets/images/zhenxing/index-menu-icon/cafe.png'),
          url: '/pages/user_sgin/index',
          show: '2',
          wap_url: '/detail/13'
        }, {
          name: '每日签到',
          pic: require('@/assets/images/zhenxing/index-menu-icon/sign.png'),
          url: '/pages/user_sgin/index',
          show: '2',
          wap_url: '/user/sign'
        }, {
          name: '每日上新',
          pic: require('@/assets/images/zhenxing/index-menu-icon/new.png'),
          url: '/pages/user_sgin/index',
          show: '2',
          wap_url: '/daliyUpdate'
        }, {
          name: '生鲜直供',
          pic: require('@/assets/images/zhenxing/index-menu-icon/fruit.png'),
          url: '/pages/user_sgin/index',
          show: '2',
          wap_url: '/goodsClassInfo?cid=3&sid=11'
        }
      ],

      screenCurrent: 0,

      //////////////////////////////////////////////////////////////////////////////// 轮播图设置开始
      swiperOption: {       // header轮播广告图
        pagination: {
          el: ".swiper-pagination",
          clickable: true
        },
        autoplay: {
          disableOnInteraction: false,
          delay: 2000
        },
        lazy: {
          loadPrevNext: true
        },
        loop: true,
        speed: 1000,
        observer: true,
        observeParents: true
      },
      swiperRoll: {        // 底部固定轮播待拼团订单信息
        direction: "vertical",
        autoplay: {
          disableOnInteraction: false,
          delay: 800
        },
        loop: true,
        speed: 1000,
        observer: true,
        observeParents: true
      },
      tabbarSwiperConfig: {
        freeMode: true,
        freeModeMomentum: false,
        freeModeMomentumRatio: 0.5,
        slidesPerView: "auto",
        observer: true,
        observeParents: true,
        resistanceRatio:0.7,
        on: {
          click: function () {
            // 这里有坑，需要注意的是：this 指向的是 swpier 实例，而不是当前的 vue， 因此借助 vm，来调用 methods 里的方法 
            // console.log(this); // -> Swiper
            // 当前活动块的索引，与activeIndex不同的是，在loop模式下不会将 复制的块 的数量计算在内。
            const realIndex = this.realIndex;
            vm.handleClickSlide(realIndex, this);
          }
        }
      },

      pageSwiperConfig: {
        direction: 'horizontal',
        loop: false,
        autoHeight: true,
      },
      //////////////////////////////////////////////////////////////////////////////// 轮播图设置结束
      
      Switch: true,

      swiperWidth:'',
      maxTranslate:'',
      maxWidth:'',

      showCoupon: false,
      showCouponType: 1,
      couponList: [],
      getCouponList: [],

      obj: null,
      showList: false,
    };
  },
  watch: {
    $route(n) {
      n.name !== "Index" ? this.showList = false : (this.getCoupon(),this.update());
    }
  },
  computed: mapGetters(["isLogin", "taskState", "userInfo"]),
  created() {
    vm = this;
  },
  mounted: function() {
    this.getHomeData();
    this.getCategoryData();
    this.getWaitCombinationOrder();
    this.update();
    setTimeout(() => {
      this.getCoupon();
    }, 1800);

    this.obj = this.$el;
    window.addEventListener("scroll",this.handleScroll); 
    if (!this.taskState.visit) {
      queryTaskFinished('visit_page').then(res => {
        console.log('查询访问任务', res);
        if (!(+res.data.isok)) {
          taskFinish('visit_page', res.data.reward).then(res => {
            console.log('设置访问任务完成', res);
            this.$store.commit('TASK_FINISHED', 'visit');
          });
        } else {
          this.$store.commit('TASK_FINISHED', 'visit');
        }
      }); 
    }
  },
  destroyed() {
    document.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    // 页面滚动监听
    handleScroll() {
      let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      this.fixedHeader = scrollTop !== 0 || this.categorySelected !== 0 ? true : false;
      this.showWaitCombinationOrderList = scrollTop < 500 ? true : false;
    },

    // tabbar点击事件
    handleClickSlide(index, swiper) { 
        let that = this;
        if (that.$refs.pageSwiper.swiper.realIndex !== that.categorySelected) {
          that.$refs.pageSwiper.swiper.slideTo(that.categorySelected, 350, false);
        }
        backTop();
        setTimeout(() => {
          that.fixedHeader = that.categorySelected !== 0 ? true : false;
        }, that.categorySelected == 0 ? 400 : 0);
        that.swiperWidth = that.$refs.tabbarSwiper.swiper.slides['1'].clientWidth;
        that.maxTranslate = that.$refs.tabbarSwiper.swiper.maxTranslate(); // 最大可移动距离（负值）
        that.maxWidth = that.maxTranslate / 2;
        that.loading_show=true;
        var boxCenter=(that.$refs.tabbarSwiper.swiper.el.clientWidth)/2,  scrollLeft = (that.categorySelected)*that.swiperWidth/2;
        that.$refs.tabbarSwiper.swiper.setTransition(200);
        if (-scrollLeft > -boxCenter+that.swiperWidth) {  //当前tab所在位置大于盒子居中位置时，回scroll盒子的首位
          that.$refs.tabbarSwiper.swiper.setTranslate(0);
          return;
        }
        if (-scrollLeft-that.swiperWidth < (that.maxTranslate+boxCenter+(that.swiperWidth/2))) {
          that.$refs.tabbarSwiper.swiper.setTranslate(that.maxTranslate);
          return;
        }
        that.$refs.tabbarSwiper.swiper.setTranslate(-scrollLeft-(that.categorySelected-3)*(that.swiperWidth/2));
    },
    categoryCurrent(index, id, item) {
      this.categorySelected = index;
      this.categoryId = id;
      setTimeout( () => {
        this.categoryItem = item; 
      }, this.$refs.pageSwiper.swiper.realIndex !== this.categorySelected ? 400 : 0);
    },

    // 页面滑动事件
    pageSlide() {
      let index = this.$refs.pageSwiper.swiper.realIndex;
      this.categoryCurrent(index, this.categoryList[index].id, this.categoryList[index].children);
      this.handleClickSlide();
    },

    // 获取特权金
    getCoupon: function() {
      let that = this;
      let q = { page: 1, limit: 6 };
      getCoupon(q).then(res => {
        that.$set(that, "getCouponList", res.data);
        console.log('cha', that.isLogin)
        if (!that.isLogin) {
          that.showCoupon=true;
          return;
        }
        if (+that.userInfo.is_new) {
          if (+that.userInfo.is_coupan) {
              that.showCouponType = 2;
              that.showCoupon = true;
          } else {
            that.showCoupon = true;
          }
        }
        console.log("getCouponList",that.showCoupon, that.getCouponList)
      });
    },

    couponClose() {
      cookie.set(HAS_COUPON_WINDOW, 1);
    },

    // 关注
    closeFollow() {
      this.followHid = false;
    },
    followTap() {
      this.followCode = true;
      this.followHid = false;
    },
    closeFollowCode() {
      this.followCode = false;
      this.followHid = true;
    },
    getFollow() {
      follow()
        .then(res => {
          this.followUrl = res.data.path;
        })
        .catch(() => {});
    },

    // 获取首页基本数据
    getHomeData: function() {
      let that = this;
      getHomeData().then(res => {
        that.status = res.status;
        that.logoUrl = res.data.logoUrl;
        that.$set(that, "banner", res.data.banner);
        that.$set(that, "menus", res.data.menus);
        that.subscribe = res.data.subscribe;
        that.setOpenShare();
      });
      this.getFollow();
    },

    // 获取分类
    getCategoryData: function() {
      let that = this;
      getCategory().then(res => {
        console.log('获取分类', res);
        for (let i in res.data) {
          if (res.data[i].children.length) {
            this.categoryList.push(res.data[i]);
          }
        }
        this.categoryList.unshift({
          cate_name: '精选热门'
        });
      });
    },

    // 获取待拼团订单
    getWaitCombinationOrder: function() {
      let that = this;
      getWaitCombinationList().then(res => {
        console.log('拼团订单', res);
        this.waitCombinationOrderList = res.data;
      });
    },

    // 更新列表显示状态
    update() {
      this.showList = true;
    },

    // 分享设置
    setOpenShare() {
      if (isWeixin()) {
        getShare().then(res => {
          var data = res.data.data;
          var configAppMessage = {
            desc: data.synopsis,
            title: data.title,
            link: location.href,
            imgUrl: data.img
          };
          openShareAll(configAppMessage);
        });
      }
    },
  }
}
</script>
